package com.zky.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.zky.gulimall.product.service.CategoryBrandRelationService;
import com.zky.gulimall.product.vo.CateLog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.product.dao.CategoryDao;
import com.zky.gulimall.product.entity.CategoryEntity;
import com.zky.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.validation.Valid;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService relationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;

    private static String CATEGORY_KEY = "catalogJson";

    private static String LOCK_KEY = "lock";


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        System.out.println("listWithTree selectList,return:" + entityList);
        if (CollectionUtils.isEmpty(entityList)) {
            return null;
        }

        //组装成父子结构
        //找出所有一级分类
        List<CategoryEntity> leve1Menu = entityList.stream().filter(item -> item.getParentCid() == 0).map(meun -> {
            meun.setChildren(getChildrens(meun, entityList));
            return meun;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return leve1Menu;
    }

    @Override
    public void removeMenuIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否在别的地方有引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCategoryPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    //@CacheEvict(value = "11",allEntries = true)
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Catorys'"),
            @CacheEvict(value = "getCatalogJson",key = "'getCatalogJson'")
    })
    @Transactional
    @Override
    public void updateCasCade(CategoryEntity category) {
        this.updateById(category);

        relationService.updateCategory(category.getCatId(), category.getName());

    }

    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Catorys() {
        log.warn("getLevel1Catorys  start...............................");
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0).or().isNull("parent_cid"));
        return entities;
    }

    @Cacheable(value = {"getCatalogJson"},key = "#root.method.name")
    @Override
    public Map<String, List<CateLog2Vo>> getCatalogJson() {
   /*     Map<String, List<CateLog2Vo>> fromRedis = getCatalogJsonFromRedis();
        if (!CollectionUtils.isEmpty(fromRedis)) {
            return fromRedis;
        }*/
        log.warn("未命中缓存，查询数据库");
        Map<String, List<CateLog2Vo>> jsonFromDb = getCatalogJsonFromDbWithRedissonLock();
    /*    Random r = new Random();
        int i = r.nextInt(5) + 1;
        redisTemplate.opsForValue().set(CATEGORY_KEY, JSON.toJSONString(jsonFromDb), i, TimeUnit.HOURS);*/
        return jsonFromDb;
    }

    public Map<String, List<CateLog2Vo>> getCatalogJsonFromDbWithRedissonLock() {

        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();
        Map<String, List<CateLog2Vo>> jsonFromDb = null;
            try {
                jsonFromDb = getCatalogJsonFromDb();
            } catch (Exception e) {
                log.error(e.getMessage());
            } finally {
               lock.unlock();
            }
            return jsonFromDb;
    }


    public Map<String, List<CateLog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        String uuid = UUID.randomUUID().toString();
        Boolean setIfAbsent = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY, uuid, 5, TimeUnit.MILLISECONDS);
        if (setIfAbsent) {
            log.warn("加锁成功");
            Map<String, List<CateLog2Vo>> jsonFromDb = null;
            try {
                jsonFromDb = getCatalogJsonFromDb();
            } catch (Exception e) {
                log.error(e.getMessage());
            } finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";

                Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(LOCK_KEY), uuid);
                if (result == null || result.equals("0")) {
                    //可能自身锁已经过期了
                    log.warn("删除锁失败");
                }
            }
            return jsonFromDb;
        } else {
            log.warn("加锁失败，等待重试");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }

    }

    public Map<String, List<CateLog2Vo>> getCatalogJsonFromDb() {

        //一次性查出所有数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1Catorys = this.getParent_cid(selectList, 0L);
        if (CollectionUtils.isEmpty(level1Catorys)) {
            log.warn("getLevel1Catorys return null");
            return null;
        }
        Map<String, List<CateLog2Vo>> listMap = level1Catorys.stream().collect(Collectors.toMap(k -> String.valueOf(k.getCatId()), v -> {
            //每个一级分类的二级分类
            List<CategoryEntity> categoryEntities = this.getParent_cid(selectList, v.getCatId());
            List<CateLog2Vo> cateLog2Vos = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(categoryEntities)) {
                cateLog2Vos = categoryEntities.stream().map(item -> {
                    CateLog2Vo cateLog2Vo = new CateLog2Vo();
                    cateLog2Vo.setId(String.valueOf(item.getCatId()));
                    cateLog2Vo.setName(item.getName());
                    cateLog2Vo.setCatalog1Id(String.valueOf(v.getCatId()));
                    //找当前二级分类的三级分类
                    List<CategoryEntity> catalogLevel3 = this.getParent_cid(selectList, item.getCatId());
                    if (!CollectionUtils.isEmpty(catalogLevel3)) {
                        List<CateLog2Vo.CateLog3Vo> log3Vos = catalogLevel3.stream().map(e -> {
                            CateLog2Vo.CateLog3Vo cateLog3Vo = new CateLog2Vo.CateLog3Vo();
                            cateLog3Vo.setId(String.valueOf(e.getCatId()));
                            cateLog3Vo.setName(e.getName());
                            cateLog3Vo.setCatalog2Id(String.valueOf(item.getCatId()));
                            return cateLog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(log3Vos);
                    }
                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }
            return cateLog2Vos;
        }));
        return listMap;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = null;
        if (!CollectionUtils.isEmpty(selectList)) {
            collect = selectList.stream().filter(item -> parent_cid.equals(item.getParentCid())).collect(Collectors.toList());
        }
        return collect;
    }


    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId != null && byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> list = all.stream().filter(item -> {
            return item.getParentCid() == root.getCatId();
        }).map(e -> {
            e.setChildren(getChildrens(e, all));
            return e;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return list;
    }


    public Map<String, List<CateLog2Vo>> getCatalogJsonFromRedis() {
        String s = redisTemplate.opsForValue().get(CATEGORY_KEY);
        if (!StringUtils.isEmpty(s)) {
            log.warn("命中缓存，result:" + s);
            Map<String, List<CateLog2Vo>> stringListMap = JSON.parseObject(s, new TypeReference<Map<String, List<CateLog2Vo>>>() {
            });
            return stringListMap;
        }
        return null;
    }

}